<script setup lang="ts">
import { useMessage, NForm, NFormItem, NInput, type FormInst, NButton, NDatePicker } from 'naive-ui'
import { ref, shallowRef, reactive } from 'vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import { useRoute } from 'vue-router'
import UploadFile from '@/views/common/UploadFile.vue'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const message = useMessage()

const formInst = shallowRef<FormInst | null>(null)
const formData = reactive({ batchId: route.params.id, supplementFileIds: new Map() } as {
  batchId: string
  depositTerm: string
  startDate: string
  endDate: string
  supplementFileIds: Map<string, string>
})
const handleUploadFinish = (e: any) => {
  formData.supplementFileIds.set(e.id, e.data.fileId)
}
const handleUploadRemove = (id: string) => {
  formData.supplementFileIds.delete(id)
}

const submitLoading = ref(false)
const handleSubmit = () => {
  if (submitLoading.value) return
  formInst.value?.validate(async (error) => {
    if (error) return

    try {
      submitLoading.value = true
      const [error, res] = await sendRequest<HttpResponse<any>>({
        module: 'batch',
        api: 'supplementFiles',
        override: {
          data: {
            ...formData,
            supplementFileIds: Array.from(formData.supplementFileIds.values()).join(',')
          }
        }
      })

      if (error) return message.error(error.message)
      if (res.code !== 0) message.error(res.msg)
      message.success(res.msg)
      window.flags.flushBatch = true
      routeReplace()
    } catch (error: any) {
      message.error(error.message)
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<template>
  <div class="add-attachments">
    <NForm
      :disabled="submitLoading"
      :model="formData"
      ref="formInst"
      label-placement="left"
      require-mark-placement="left"
      label-width="100rem"
    >
      <NFormItem label="开始时间：">
       <NDatePicker input-readonly
          placeholder="请输入"
          style="flex: 1"
          v-model:formatted-value="formData.startDate"
          format="yyyy-MM-dd"
        />
      </NFormItem>
      <NFormItem label="结束时间：">
       <NDatePicker input-readonly
          placeholder="请输入"
          style="flex: 1"
          v-model:formatted-value="formData.endDate"
          format="yyyy-MM-dd"
        />
      </NFormItem>
      <NFormItem
        label="代存期限："
        path="depositTerm"
        :rule="{
          trigger: ['blur', 'input'],
          message: '存期限不能超过100字',
          validator: (_, value) => (value ? value.length <= 100 : true)
        }"
      >
        <NInput
          placeholder="请输入"
          v-model:value="formData.depositTerm"
        />
      </NFormItem>
      <NFormItem
        label="附件："
        path="supplementFileIds"
        :rule="{
          required: true,
          message: '附件为必填项，请上传附件',
          validator: (_, value) => value.size > 0
        }"
      >
        <UploadFile
          :max="10"
          multiple
          @finish="handleUploadFinish"
          @remove="handleUploadRemove"
        >
          <template #trigger="{ handleClick }">
            <n-button
              @click="handleClick"
              color="#6CB187"
              ghost
              size="small"
            >
              点击上传
            </n-button>
          </template>
        </UploadFile>
      </NFormItem>
      <!-- <span style="padding-left: 100rem">
        带
        <span style="color: #fd4a29">*</span>
        为必填项
      </span> -->
    </NForm>
  </div>

  <FixedAction>
    <div class="add-attachments-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="routeReplace"
      >
        取消
      </NButton>

      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.add-attachments {
  flex: 1;
  height: 100%;
  padding: 25rem 56rem 0 36rem;

  .n-form {
    min-width: 618rem;
    padding: 25rem 33rem 27rem 20rem;
    background-color: #ebeceb;
  }
}

.add-attachments-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}
</style>
